import { defineStore } from "pinia"
import { getUserInfo } from "@/apis/user"
import { ref } from "vue"
import { useCartStore } from "./cartStore"
import { mergeCart } from "@/apis/cart"

export const useUserStore = defineStore('user', () => {
  const userInfo = ref({})
  const clearUserInfo = () => {
    userInfo.value = {}
  }

  const FetchUserInfo = async ({ account, password }) => {
    // 获取用户信息
    const res = await getUserInfo({ account, password })
    // 保存用户信息
    userInfo.value = res.data.result
    const cartStore = useCartStore()

    const cartArr = cartStore.cartList.map(item => ({
      skuId: String(item.skuId), // 确保 skuId 是字符串
      selected: String(item.selected), // 确保 selected 是字符串
      count: Number(item.count) // 确保 count 是整数
    }))

    // 合并购物车
    await mergeCart(cartArr)
    // 重新获取数据
    cartStore.getCart()
  }

  return {
    userInfo,
    FetchUserInfo,
    clearUserInfo
  }
}, {
  persist: true
})
